<?php

class OrderController extends Controller {

    public $layout = '//layouts/homemain';
    public $breadcrumbs = false;
    public $homesite = false;

//    public function filters() {
//        return array(
//            'accessControl', // perform access control for CRUD operations
//        );
//    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to access 'index' and 'view' actions.
//                'actions' => array('confirmation'),
                'users' => array('*'),
            ),
//            array('deny', // allow all users to access 'index' and 'view' actions.
//                'actions' => array('register', 'login'),
//                'users' => array('?'),
//            ),
            array('allow', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function init() {
        $cs = Yii::app()->clientScript;
        $cs->registerCssFile(Yii::app()->baseUrl . '/css/common.css');
        $cs->registerCssFile(Yii::app()->baseUrl . '/css/v3/n_common.css');
        $cs->registerCssFile(Yii::app()->baseUrl . '/css/order.css');
        $cs->registerScriptFile(Yii::app()->request->baseUrl . "/js/common.js", CClientScript::POS_HEAD);
        $cs->registerScriptFile(Yii::app()->request->baseUrl . "/js/v3/n_common.js", CClientScript::POS_HEAD);
        $cs->registerScriptFile(Yii::app()->request->baseUrl . "/js/zhbform.js", CClientScript::POS_HEAD);
        $cs->registerCoreScript('jquery');
        $cs->registerCoreScript('jquery.ui');
        $cs->registerScriptFile(Yii::app()->request->baseUrl . "/js/jquery.placeholder.js", CClientScript::POS_HEAD);
    }

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page' => array(
                'class' => 'CViewAction',
            ),
        );
    }

    public function actionError() {
        if ($error = Yii::app()->errorHandler->error) {
            if (Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    public function actionConfirmation() {
        $cs = Yii::app()->clientScript;
        $cs->registerScriptFile(Yii::app()->request->baseUrl . "/js/order.js", CClientScript::POS_HEAD);
        if (!Yii::app()->user->isGuest) {
            $model = new OrderForm('addUserOrder');
            $api = new Api('account');

            /*
             * 获取用户收货地址
             */
            $apiurl = "/LdAccountServer/order/getUserContactInfo";
            $params = array(
                'GetUserContactInfoReq' => array(
                    'userId' => Yii::app()->user->id
                )
            );
            $row = $api->apiclient($apiurl, $params);

            for ($i = 0; $i < count($row['GetUserContactInfoRsp']['list']); $i++) {
                if ($row['GetUserContactInfoRsp']['list'][$i]['defaultAddress'] == 1) {
                    $defaultAddress = $row['GetUserContactInfoRsp']['list'][$i]['id'];
                }
            }

            $model->userContactInfoId = $defaultAddress;  // 设置默认收货地址为选中状态

            /*
             * 遍历收货时间
             */
            $date = array(
                '0' => array(
                    'v' => Yii::app()->params['today'],
                    'n' => Yii::app()->params['today'] . '(今天)'
                ),
//                '1' => array(
//                    'v' => Yii::app()->params['tomorrow'],
//                    'n' => Yii::app()->params['tomorrow'] . '(明天)'
//                )
            );

            $nowtime = time() + 1800;
            $endtime = strtotime(date('Y-m-d 14:00:00', time()));
            $fullstarttime = strtotime(date('Y-m-d 11:00:00', time()));
            if ($nowtime < $fullstarttime) {
                $starttime = $fullstarttime;
            } else {
                $is = date('i', $nowtime);
                if ((int) $is > 0 && (int) $is < 15) {
                    $newi = '15';
                } elseif ((int) $is > 15 && (int) $is < 30) {
                    $newi = '30';
                } elseif ((int) $is > 30 && (int) $is < 45) {
                    $newi = '45';
                } elseif ((int) $is > 45) {
                    $newi = '00';
                }
                $startH = date('H', $nowtime);
                $starttime = strtotime(date('Y-m-d ' . $startH . ':' . $newi . ':00', time()));
            }
//            echo date('Y-m-d H:i:s',$starttime);
//            echo date('Y-m-d H:i:s',$nowtime);
            for ($ik = 0; $ik < 14; $ik++) {
                if ($starttime <= $endtime) {
                    $newFormatTime = date('H:i', $starttime + ($ik * 900));
                    if (strtotime(date('Y-m-d ' . $newFormatTime . ':00', time())) <= $endtime) {
                        $ordertime[$newFormatTime] = $newFormatTime;
                    }
                } else {
                    $ordertime = array('' => '已超过送餐时间');
                }
            }
//            print_r($ordertime);
            if (isset($_POST['ajax']) && $_POST['ajax'] === 'order-form') {
                echo CActiveForm::validate($model);
                Yii::app()->end();
            }

            if (isset($_POST['OrderForm'])) {
                $model->attributes = $_POST['OrderForm'];

                if ($model->validate() && $model->addUserOrder()) {
                    if ($model->addUserOrder() === true) {
                        $userContactInfoId = $model->userContactInfoId;
                    } else {
                        $userContactInfoId = $model->addUserOrder();
                    }

                    $sellerId = $model->sellerId;
                    $productSkuId = $model->productSkuId;
                    $amount = $model->amount;
                    for ($i = 0; $i < count($sellerId); $i++) {
                        $orderItems[$i]['sellerId'] = $sellerId[$i];
                        $orderItems[$i]['productSkuId'] = $productSkuId[$i];
                        $orderItems[$i]['amount'] = $amount[$i];
                    }

                    $apiurl_addUserOrder = "/LdAccountServer/order/addUserOrder";
                    $params_addUserOrder = array(
                        'AddUserOrderReq' => array(
                            'userId' => Yii::app()->user->id,
                            'deliverFee' => $model->deliverFee,
                            'note' => $model->note,
                            'paymentWay' => $model->paymentWay,
                            'productTotalPrice' => $model->productTotalPrice,
                            'orderState' => $model->orderState,
                            'totalPrice' => $model->deliverFee + $model->productTotalPrice,
                            'receiptDate' => $model->receiptDate,
                            'receiptTime' => $model->receiptTime,
                            'userContactInfoId' => $userContactInfoId,
                            'orderItems' => $orderItems,
                        )
                    );
//                    print_r($params_addUserOrder);

                    $row_addUserOrder = $api->apiclient($apiurl_addUserOrder, $params_addUserOrder);
                    if ($row_addUserOrder['code'] == 0) {
                        $ids = $model->id;
                        foreach ($ids as $keyid => $vid) {
                            $apiurl_delUserCart = "/LdAccountServer/order/delUserCart";
                            $params_delUserCart = array(
                                'DelUserCartReq' => array(
                                    'id' => $vid,
                                )
                            );

                            $row_delUserCart = $api->apiclient($apiurl_delUserCart, $params_delUserCart);
                        }

                        $this->redirect(Yii::app()->baseUrl . '/order/payways/' . urlencode(base64_encode($row_addUserOrder['AddUserOrderRsp']['userId'] . '|' . $row_addUserOrder['AddUserOrderRsp']['orderId'])));
                    } else {
                        Yii::app()->user->setFlash('message', $row_addUserOrder['ExceptionRsp']['msg']);
                    }
                }
            }

            $this->render('confirmation', array('date' => $date, 'model' => $model, 'addresslist' => $row,'ordertime'=>$ordertime));
        } else {
            $this->redirect(Yii::app()->baseUrl);
        }
    }

    public function actionPayWays() {
//        echo Yii::app()->baseUrl . '/order/payways/' . urlencode(base64_encode('3|2014071523480210000006'));
        if (!Yii::app()->user->isGuest) {
            $model = new PayForm();

            if (isset($_POST['PayForm'])) {
                $value = Yii::app()->request->getParam("PayForm");
                $this->renderPartial('payways', array('model' => $model, 'value' => $value));
            } else {
                $model->paytype = 'alipay';

                $auth = urldecode(base64_decode($_GET['auth']));
                $autharr = explode('|', $auth);
                $orderId = $autharr['1'];

                $api = new Api('account');
                $apiurl = "/LdAccountServer/order/getOrderItem";
                $params = array(
                    'GetOrderItemReq' => array(
                        'orderId' => $orderId
                    )
                );
                $row = $api->apiclient($apiurl, $params);

                $apiurl_hb = "/LdAccountServer/userAccount/getBuyerCoupons";
                $params_hb = array(
                    'GetBuyerCouponsReq' => array(
                        'buyerId' => Yii::app()->user->id
                    )
                );
                $row_hb = $api->apiclient($apiurl_hb, $params_hb);
//            print_r($row);

                $this->render('payways', array('model' => $model, 'orderinfo' => $row['GetOrderItemRsp'], 'row_hb' => $row_hb['GetBuyerCouponsListRsp']['list']));
            }
        } else {
            $this->redirect(Yii::app()->baseUrl);
        }
    }

    public function actionPay() {
        if (!Yii::app()->user->isGuest) {

            $model = new PayForm();

            if (isset($_POST['ajax']) && $_POST['ajax'] === 'pay-form') {
                echo CActiveForm::validate($model);
                Yii::app()->end();
            }

            if (isset($_POST['PayForm'])) {
                $api = new Api('account');
                $apiurl = "/LdAccountServer/userAccount/updateBuyerCoupons";


                $model->attributes = $_POST['PayForm'];
//                if ($model->validate()) {
                if (count($model->coupons) > 0) {
                    $couponsPotal = 0;
                    foreach ($model->coupons as $key => $value) {
                        $couponsarr = explode('|', $value);
                        $couponsId = $couponsarr['0'];
                        $couponsMoney = $couponsarr['1'];
                        $params = array(
                            'UpdateBuyerCouponsReq' => array(
                                'couponsId' => $couponsId,
                                'status' => '1'
                            )
                        );
                        $row = $api->apiclient($apiurl, $params);
                        if ($couponsMoney > 0) {
                            $couponsPotal += $couponsMoney;
                        }
                    }
                }

                if ($couponsPotal > 0) {
                    $apiurl_updateOrder = '/LdAccountServer/order/updateOrderTotal';
                    $params_updateOrder = array(
                        'UpdateOrderTotalReq' => array(
                            'orderId' => $model->WIDout_trade_no,
                            'totalPrice' => $model->WIDtotal_fee
                        )
                    );
                    $row_updateOrder = $api->apiclient($apiurl_updateOrder, $params_updateOrder);
                }
                if ($model->paytype == 'alipay') {
                    include_once './alipay/alipay.config.php';
                    require_once("./alipay/lib/alipay_submit.class.php");
                    //支付类型
                    $payment_type = "1";
                    //必填，不能修改
                    //服务器异步通知页面路径
//                        $notify_url = "http://www.xxx.com/create_direct_pay_by_user-PHP-UTF-8/notify_url.php";
//                        $notify_url = 'http://www.ldfood.cn/order/alipaynotify'; 
                    $notify_url = Yii::app()->request->hostInfo . Yii::app()->baseUrl . "/order/alipaynotify/";
                    //需http://格式的完整路径，不能加?id=123这类自定义参数
                    //页面跳转同步通知页面路径
//                        $return_url = 'http://www.ldfood.cn/order/paydone'; 
                    $return_url = Yii::app()->request->hostInfo . Yii::app()->baseUrl . "/order/paydone/";
                    //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/
                    //卖家支付宝帐户
                    $seller_email = $alipay_config['email'];
                    //必填
                    //商户订单号
                    $out_trade_no = $model->WIDout_trade_no;
                    //商户网站订单系统中唯一订单号，必填
                    //订单名称
                    $subject = "灵动生活-点餐信息";
                    //必填
                    //付款金额
                    $total_fee = $model->WIDtotal_fee;
                    //必填
                    //订单描述
                    $body = '灵动生活-网上点餐';
                    //商品展示地址
                    $show_url = Yii::app()->request->hostInfo . Yii::app()->baseUrl . '/order/payways/' . $model->orderid;
//                        $show_url = $alipay_config['show_url'];
                    //需以http://开头的完整路径，例如：http://www.xxx.com/myorder.html
                    //防钓鱼时间戳
                    $anti_phishing_key = "";
                    //若要使用请调用类文件submit中的query_timestamp函数
                    //客户端的IP地址
                    $exter_invoke_ip = "";
                    //非局域网的外网IP地址，如：221.0.0.1
                    //构造要请求的参数数组，无需改动
                    $parameter = array(
                        "service" => "create_direct_pay_by_user",
                        "partner" => trim($alipay_config['partner']),
                        "payment_type" => $payment_type,
                        "notify_url" => $notify_url,
                        "return_url" => $return_url,
                        "seller_email" => $seller_email,
                        "out_trade_no" => $out_trade_no,
                        "subject" => $subject,
                        "total_fee" => $total_fee,
                        "body" => $body,
                        "show_url" => $show_url,
                        "anti_phishing_key" => $anti_phishing_key,
                        "exter_invoke_ip" => $exter_invoke_ip,
                        "_input_charset" => trim(strtolower($alipay_config['input_charset']))
                    );
//                        print_r($parameter);
                    //建立请求
                    $alipaySubmit = new AlipaySubmit($alipay_config);
                    $html_text = $alipaySubmit->buildRequestForm($parameter, "get", "确认");
                    $this->renderPartial('pay', array('model' => $model, 'html_text' => $html_text));
//                        $this->renderPartial('pay', array('model' => $model));
                } else {
                    include_once './tenpay/classes/RequestHandler.class.php';
                    require_once("./tenpay/tenpay_config.php");

                    /* 获取提交的订单号 */
                    $out_trade_no = $model->WIDout_trade_no;
                    /* 获取提交的商品名称 */
                    $product_name = '灵动生活-点餐信息';
                    /* 获取提交的商品价格 */
                    $order_price = $model->WIDtotal_fee;
                    /* 获取提交的备注信息 */
                    $remarkexplain = $model->note;
                    /* 支付方式 */
                    $trade_mode = 1;

                    $strDate = date("Ymd");
                    $strTime = date("His");

                    /* 商品价格（包含运费），以分为单位 */
                    $total_fee = $order_price * 100;

                    /* 商品名称 */
                    $desc = "商品：" . $product_name; // . ",备注:" . $remarkexplain;

                    /* 创建支付请求对象 */
                    $reqHandler = new RequestHandler();
                    $reqHandler->init();
                    $reqHandler->setKey($key);
                    $reqHandler->setGateUrl("https://gw.tenpay.com/gateway/pay.htm");

//----------------------------------------
//设置支付参数 
//----------------------------------------
                    $reqHandler->setParameter("partner", $partner);
                    $reqHandler->setParameter("out_trade_no", $out_trade_no);
                    $reqHandler->setParameter("total_fee", $total_fee);  //总金额
                    $reqHandler->setParameter("return_url", $return_url);
                    $reqHandler->setParameter("notify_url", $notify_url);
                    $reqHandler->setParameter("body", $desc);
                    $reqHandler->setParameter("bank_type", $model->paytype);     //银行类型，默认为财付通
//用户ip
                    $reqHandler->setParameter("spbill_create_ip", $_SERVER['REMOTE_ADDR']); //客户端IP
                    $reqHandler->setParameter("fee_type", "1");               //币种
                    $reqHandler->setParameter("subject", "商品：" . $product_name);          //商品名称，（中介交易时必填）
//系统可选参数
                    $reqHandler->setParameter("sign_type", "MD5");       //签名方式，默认为MD5，可选RSA
                    $reqHandler->setParameter("service_version", "1.0");    //接口版本号
                    $reqHandler->setParameter("input_charset", "utf-8");      //字符集
                    $reqHandler->setParameter("sign_key_index", "1");       //密钥序号
//业务可选参数
                    $reqHandler->setParameter("attach", "");                //附件数据，原样返回就可以了
                    $reqHandler->setParameter("product_fee", "");           //商品费用
                    $reqHandler->setParameter("transport_fee", "0");         //物流费用
                    $reqHandler->setParameter("time_start", date("YmdHis"));  //订单生成时间
                    $reqHandler->setParameter("time_expire", "");             //订单失效时间
                    $reqHandler->setParameter("buyer_id", "");                //买方财付通帐号
                    $reqHandler->setParameter("goods_tag", "");               //商品标记
                    $reqHandler->setParameter("trade_mode", $trade_mode);              //交易模式（1.即时到帐模式，2.中介担保模式，3.后台选择（卖家进入支付中心列表选择））
                    $reqHandler->setParameter("transport_desc", "");              //物流说明
                    $reqHandler->setParameter("trans_type", "1");              //交易类型
                    $reqHandler->setParameter("agentid", "");                  //平台ID
                    $reqHandler->setParameter("agent_type", "");               //代理模式（0.无代理，1.表示卡易售模式，2.表示网店模式）
                    $reqHandler->setParameter("seller_id", "");                //卖家的商户号
//请求的URL
                    $reqUrl = $reqHandler->getRequestURL();
                    $this->redirect($reqUrl);
//                    $html_text .= '<a href="' . $reqUrl . '" target="_blank">支付</a>';
//                        $html_text.= "<div class=\"nfl\">";
//                        $html_text.= "<div class=\"f_c altw\">";
//                        $html_text.= "<div id=\"messagetext\" class=\"alert_error\">";
//                        $html_text.= "<p>本支付方式还未开通<script type=\"text/javascript\" reload=\"1\">//setTimeout(\"window.location.href ='http://wh.whtaxi.com/zp/';\", 3000);</script></p>";
//                        $html_text.= "<p class=\"alert_btnleft\"><a href=\"javascript:history.go(-1);\">返回上一步</a></p>";
//                        $html_text.= "</div>";
//                        $html_text.= "</div>";
//                        $html_text.= "</div>";

                    $this->render('pay', array('model' => $model, 'html_text' => $html_text));
                }
//                }
            }
        } else {
            $this->redirect(Yii::app()->baseUrl);
        }
    }

    public function actionPaydone() {
        $cs = Yii::app()->clientScript;
        $cs->registerCssFile(Yii::app()->baseUrl . '/css/login.css');

        include_once './alipay/alipay.config.php';
        include_once './alipay/lib/alipay_notify.class.php';

        $api = new Api('account');

//        $alipayNotify = new AlipayNotify($alipay_config);
//        $verify_result = $alipayNotify->verifyReturn();
        $verify_result = true;
        if ($verify_result) {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码
            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表
            //商户订单号
            $out_trade_no = $_GET['out_trade_no'];

            //支付宝交易号

            $trade_no = $_GET['trade_no'];

            //交易状态
            $trade_status = $_GET['trade_status'];


            if ($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
                $row = "交易成功<br />" . $_GET['trade_status'];
            } else {
                $row = "交易失败<br />" . $_GET['trade_status'];
            }

            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        } else {
            //验证失败
            //如要调试，请看alipay_notify.php页面的verifyReturn函数
            $row = "交易失败";
        }

        $this->render('paydone', array('model' => $row, 'orderinfo' => $row_orderinfo['GetOrderItemRsp']));
    }

    public function actionAlipaynotify() {

        include_once './alipay/alipay.config.php';
        include_once './alipay/lib/alipay_notify.class.php';
//        logResult($row . '-' . $out_trade_no . 'dd-dd' . $trade_no . 'dd-dd' . $trade_status);
        $api = new Api('account');
//计算得出通知验证结果
        $alipayNotify = new AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();
        $row = (string) $verify_result;
//        logResult($row . '-' . $out_trade_no . 'dd-dd' . $trade_no . 'dd-dd222' . $trade_status);
        if ($row == '1') {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代
            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];

            //支付宝交易号
            $trade_no = $_POST['trade_no'];

            //交易状态
            $trade_status = $_POST['trade_status'];
//            echo $out_trade_no;
//            echo $trade_no;
//            echo $trade_status;
//            logResult($row . '-' . $out_trade_no . '1111-1111' . $trade_no . 'dd-dd' . $trade_status);
            if ($_POST['trade_status'] == 'TRADE_FINISHED') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //该种交易状态只在两种情况下出现
                //1、开通了普通即时到账，买家付款成功后。
                //2、开通了高级即时到账，从该笔交易成功时间算起，过了签约时的可退款时限（如：三个月以内可退款、一年以内可退款等）后。
                //调试用，写文本函数记录程序运行情况是否正常
                $apiurl = "/LdAccountServer/order/updateOrderState";  //付款成功后更改订单状态
                $params = array(
                    'UpdateOrderStateReq' => array(
                        'id' => $out_trade_no,
                        'orderState' => '3'//0-订单已取消，1-等待付款，2-付款失败，3-等待收货,确认收货并评价，4-正在发货，5-等待收货，6-已确认，已评价，7-退款
                    )
                );
                $row = $api->apiclient($apiurl, $params);

                $apiurl_orderinfo = "/LdAccountServer/order/getOrderItem";  //获取订单信息
                $params_orderinfo = array(
                    'GetOrderItemReq' => array(
                        'orderId' => $out_trade_no,
                    )
                );
                $row_orderinfo = $api->apiclient($apiurl_orderinfo, $params_orderinfo);

                foreach ($row_orderinfo['GetOrderItemRsp']['orderItems'] as $key => $value) {  // 增加商品购买数量+1
                    @file_get_contents("http://" . Yii::app()->params['apiHostProduct'] . ":" . Yii::app()->params['apiPortProduct'] . "/ProductCenter/UpdateProductBehaver/?productId=&type=1&productSkuId=" . $value['productSkuId']);
                }
//                logResult($out_trade_no . '1-' . $trade_no . '1-' . $trade_status);
            } elseif ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //该种交易状态只在一种情况下出现——开通了高级即时到账，买家付款成功后。
                //调试用，写文本函数记录程序运行情况是否正常
                $apiurl = "/LdAccountServer/order/updateOrderState";  //付款成功后更改订单状态
                $params = array(
                    'UpdateOrderStateReq' => array(
                        'id' => $out_trade_no,
                        'orderState' => '3'//0-订单已取消，1-等待付款，2-付款失败，3-等待收货,确认收货并评价，4-正在发货，5-等待收货，6-已确认，已评价，7-退款
                    )
                );
                $row = $api->apiclient($apiurl, $params);

                $apiurl_orderinfo = "/LdAccountServer/order/getOrderItem";  //获取订单信息
                $params_orderinfo = array(
                    'GetOrderItemReq' => array(
                        'orderId' => $out_trade_no,
                    )
                );
                $row_orderinfo = $api->apiclient($apiurl_orderinfo, $params_orderinfo);

                foreach ($row_orderinfo['GetOrderItemRsp']['orderItems'] as $key => $value) {  // 增加商品购买数量+1
                    @file_get_contents("http://" . Yii::app()->params['apiHostProduct'] . ":" . Yii::app()->params['apiPortProduct'] . "/ProductCenter/UpdateProductBehaver/?productId=&type=1&productSkuId=" . $value['productSkuId']);
                }
//                logResult($out_trade_no . '2-2' . $trade_no . '2-2' . $trade_status);
            }

            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
//            logResult($out_trade_no . '3-3' . $trade_no . '-' . $trade_status);
            echo "success";  //请不要修改或删除
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        } else {
            //验证失败
            echo "fail";

            //调试用，写文本函数记录程序运行情况是否正常
//            logResult($out_trade_no . 'f-f' . $trade_no . 'f-f' . $trade_status);
        }

        $this->renderPartial('alipaynotify');
    }
    
    public function actionAlipayrsanotify() {

        include_once './alipay/alipay_rsa.config.php';
        include_once './alipay/lib/alipay_notify_rsa.class.php';
//        logResult($row . '-' . $out_trade_no . '-' . $trade_no . '-' . $trade_status.'-1');
        $api = new Api('account');
//计算得出通知验证结果
        $alipayNotify = new AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();
        $row = (string) $verify_result;
//        logResult($row . '-' . $out_trade_no . '-' . $trade_no . '-' . $trade_status.'-'.$verify_result.'-2');
        if ($row == '1') {//验证成功
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代
            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
            //商户订单号
            $out_trade_no = $_POST['out_trade_no'];

            //支付宝交易号
            $trade_no = $_POST['trade_no'];

            //交易状态
            $trade_status = $_POST['trade_status'];
//            echo $out_trade_no;
//            echo $trade_no;
//            echo $trade_status;
//            logResult($row . '-' . $out_trade_no . '1111-1111' . $trade_no . 'dd-dd' . $trade_status);
            if ($_POST['trade_status'] == 'TRADE_FINISHED') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //该种交易状态只在两种情况下出现
                //1、开通了普通即时到账，买家付款成功后。
                //2、开通了高级即时到账，从该笔交易成功时间算起，过了签约时的可退款时限（如：三个月以内可退款、一年以内可退款等）后。
                //调试用，写文本函数记录程序运行情况是否正常
                $apiurl = "/LdAccountServer/order/updateOrderState";  //付款成功后更改订单状态
                $params = array(
                    'UpdateOrderStateReq' => array(
                        'id' => $out_trade_no,
                        'orderState' => '3'//0-订单已取消，1-等待付款，2-付款失败，3-等待收货,确认收货并评价，4-正在发货，5-等待收货，6-已确认，已评价，7-退款
                    )
                );
                $row = $api->apiclient($apiurl, $params);

                $apiurl_orderinfo = "/LdAccountServer/order/getOrderItem";  //获取订单信息
                $params_orderinfo = array(
                    'GetOrderItemReq' => array(
                        'orderId' => $out_trade_no,
                    )
                );
                $row_orderinfo = $api->apiclient($apiurl_orderinfo, $params_orderinfo);

                foreach ($row_orderinfo['GetOrderItemRsp']['orderItems'] as $key => $value) {  // 增加商品购买数量+1
                    @file_get_contents("http://" . Yii::app()->params['apiHostProduct'] . ":" . Yii::app()->params['apiPortProduct'] . "/ProductCenter/UpdateProductBehaver/?productId=&type=1&productSkuId=" . $value['productSkuId']);
                }
//                logResult($out_trade_no . '1-' . $trade_no . '1-' . $trade_status);
            } elseif ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //该种交易状态只在一种情况下出现——开通了高级即时到账，买家付款成功后。
                //调试用，写文本函数记录程序运行情况是否正常
                $apiurl = "/LdAccountServer/order/updateOrderState";  //付款成功后更改订单状态
                $params = array(
                    'UpdateOrderStateReq' => array(
                        'id' => $out_trade_no,
                        'orderState' => '3'//0-订单已取消，1-等待付款，2-付款失败，3-等待收货,确认收货并评价，4-正在发货，5-等待收货，6-已确认，已评价，7-退款
                    )
                );
                $row = $api->apiclient($apiurl, $params);

                $apiurl_orderinfo = "/LdAccountServer/order/getOrderItem";  //获取订单信息
                $params_orderinfo = array(
                    'GetOrderItemReq' => array(
                        'orderId' => $out_trade_no,
                    )
                );
                $row_orderinfo = $api->apiclient($apiurl_orderinfo, $params_orderinfo);

                foreach ($row_orderinfo['GetOrderItemRsp']['orderItems'] as $key => $value) {  // 增加商品购买数量+1
                    @file_get_contents("http://" . Yii::app()->params['apiHostProduct'] . ":" . Yii::app()->params['apiPortProduct'] . "/ProductCenter/UpdateProductBehaver/?productId=&type=1&productSkuId=" . $value['productSkuId']);
                }
//                logResult($out_trade_no . '2-2' . $trade_no . '2-2' . $trade_status);
            }

            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
//            logResult($out_trade_no . '3-3' . $trade_no . '-' . $trade_status);
            echo "success";  //请不要修改或删除
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        } else {
            //验证失败
            echo "fail";

            //调试用，写文本函数记录程序运行情况是否正常
//            logResult($out_trade_no . 'f-f' . $trade_no . 'f-f' . $trade_status);
        }

        $this->renderPartial('alipayrsanotify');
    }

    public function actionTenpaynotify() {
        require ("./tenpay/classes/ResponseHandler.class.php");
        require ("./tenpay/classes/RequestHandler.class.php");
        require ("./tenpay/classes/client/ClientResponseHandler.class.php");
        require ("./tenpay/classes/client/TenpayHttpClient.class.php");
        require ("./tenpay/classes/function.php");
        require_once ("./tenpay/tenpay_config.php");

        log_result("进入后台回调页面");


        /* 创建支付应答对象 */
        $resHandler = new ResponseHandler();
        $resHandler->setKey($key);

        //判断签名
        if ($resHandler->isTenpaySign()) {

            //通知id
            $notify_id = $resHandler->getParameter("notify_id");

            //通过通知ID查询，确保通知来至财付通
            //创建查询请求
            $queryReq = new RequestHandler();
            $queryReq->init();
            $queryReq->setKey($key);
            $queryReq->setGateUrl("https://gw.tenpay.com/gateway/simpleverifynotifyid.xml");
            $queryReq->setParameter("partner", $partner);
            $queryReq->setParameter("notify_id", $notify_id);

            //通信对象
            $httpClient = new TenpayHttpClient();
            $httpClient->setTimeOut(5);
            //设置请求内容
            $httpClient->setReqContent($queryReq->getRequestURL());

            //后台调用
            if ($httpClient->call()) {
                //设置结果参数
                $queryRes = new ClientResponseHandler();
                $queryRes->setContent($httpClient->getResContent());
                $queryRes->setKey($key);

                if ($resHandler->getParameter("trade_mode") == "1") {
                    //判断签名及结果（即时到帐）
                    //只有签名正确,retcode为0，trade_state为0才是支付成功
                    if ($queryRes->isTenpaySign() && $queryRes->getParameter("retcode") == "0" && $resHandler->getParameter("trade_state") == "0") {
                        log_result("即时到帐验签ID成功");
                        //取结果参数做业务处理
                        $out_trade_no = $resHandler->getParameter("out_trade_no");
                        //财付通订单号
                        $transaction_id = $resHandler->getParameter("transaction_id");
                        //金额,以分为单位
                        $total_fee = $resHandler->getParameter("total_fee");
                        //如果有使用折扣券，discount有值，total_fee+discount=原请求的total_fee
                        $discount = $resHandler->getParameter("discount");

                        //------------------------------
                        //处理业务开始
                        //------------------------------
                        //处理数据库逻辑
                        //注意交易单不要重复处理
                        //注意判断返回金额
                        //------------------------------
                        //处理业务完毕
                        //------------------------------
                        log_result("即时到帐后台回调成功");
                        echo "success";
                    } else {
                        //错误时，返回结果可能没有签名，写日志trade_state、retcode、retmsg看失败详情。
                        //echo "验证签名失败 或 业务错误信息:trade_state=" . $resHandler->getParameter("trade_state") . ",retcode=" . $queryRes->                         getParameter("retcode"). ",retmsg=" . $queryRes->getParameter("retmsg") . "<br/>" ;
                        log_result("即时到帐后台回调失败");
                        echo "fail";
                    }
                } elseif ($resHandler->getParameter("trade_mode") == "2") {
                    //判断签名及结果（中介担保）
                    //只有签名正确,retcode为0，trade_state为0才是支付成功
                    if ($queryRes->isTenpaySign() && $queryRes->getParameter("retcode") == "0") {
                        log_result("中介担保验签ID成功");
                        //取结果参数做业务处理
                        $out_trade_no = $resHandler->getParameter("out_trade_no");
                        //财付通订单号
                        $transaction_id = $resHandler->getParameter("transaction_id");


                        //------------------------------
                        //处理业务开始
                        //------------------------------
                        //处理数据库逻辑
                        //注意交易单不要重复处理
                        //注意判断返回金额

                        log_result("中介担保后台回调，trade_state=" . $resHandler->getParameter("trade_state"));
                        switch ($resHandler->getParameter("trade_state")) {
                            case "0": //付款成功

                                break;
                            case "1": //交易创建

                                break;
                            case "2": //收获地址填写完毕

                                break;
                            case "4": //卖家发货成功

                                break;
                            case "5": //买家收货确认，交易成功

                                break;
                            case "6": //交易关闭，未完成超时关闭

                                break;
                            case "7": //修改交易价格成功

                                break;
                            case "8": //买家发起退款

                                break;
                            case "9": //退款成功

                                break;
                            case "10": //退款关闭			

                                break;
                            default:
                                //nothing to do
                                break;
                        }


                        //------------------------------
                        //处理业务完毕
                        //------------------------------
                        echo "success";
                    } else {
                        //错误时，返回结果可能没有签名，写日志trade_state、retcode、retmsg看失败详情。
                        //echo "验证签名失败 或 业务错误信息:trade_state=" . $resHandler->getParameter("trade_state") . ",retcode=" . $queryRes->             										       getParameter("retcode"). ",retmsg=" . $queryRes->getParameter("retmsg") . "<br/>" ;
                        log_result("中介担保后台回调失败");
                        echo "fail";
                    }
                }



                //获取查询的debug信息,建议把请求、应答内容、debug信息，通信返回码写入日志，方便定位问题
                /*
                  echo "<br>------------------------------------------------------<br>";
                  echo "http res:" . $httpClient->getResponseCode() . "," . $httpClient->getErrInfo() . "<br>";
                  echo "query req:" . htmlentities($queryReq->getRequestURL(), ENT_NOQUOTES, "GB2312") . "<br><br>";
                  echo "query res:" . htmlentities($queryRes->getContent(), ENT_NOQUOTES, "GB2312") . "<br><br>";
                  echo "query reqdebug:" . $queryReq->getDebugInfo() . "<br><br>" ;
                  echo "query resdebug:" . $queryRes->getDebugInfo() . "<br><br>";
                 */
            } else {
                //通信失败
                echo "fail";
                //后台调用通信失败,写日志，方便定位问题
                echo "<br>call err:" . $httpClient->getResponseCode() . "," . $httpClient->getErrInfo() . "<br>";
            }
        } else {
            echo "<br/>" . "认证签名失败" . "<br/>";
            echo $resHandler->getDebugInfo() . "<br>";
        }

        $this->renderPartial('tenpaynotify');
    }

    public function actionReceipt() {
        if (!Yii::app()->user->isGuest) {
            $api = new Api('account');
            $model = new OrderForm('addCommont');
            $commonclass = new CommonClass();

            if (isset($_POST['ajax']) && $_POST['ajax'] === 'commont-form') {
                echo CActiveForm::validate($model);
                Yii::app()->end();
            }

            if (isset($_POST['OrderForm'])) {
                $model->attributes = $_POST['OrderForm'];
                if ($model->validate()) {
                    $formrow = $model->addCommont();
                    if ($formrow['code'] > 0) {
                        $apiurl_state = "/LdAccountServer/order/updateOrderState";  //付款成功后更改订单状态
                        $params_state = array(
                            'UpdateOrderStateReq' => array(
                                'id' => $model->orderId,
                                'orderState' => '6'//0-订单已取消，1-等待付款，2-付款失败，3-等待收货,确认收货并评价，4-正在发货，5-等待收货，6-已确认，已评价，7-退款
                            )
                        );
//                        echo $model->orderId;
                        $row_state = $api->apiclient($apiurl_state, $params_state);
                        if ($row_state == 0) {
                            $showmessage = $commonclass->showMessage('网络连接超时，请稍后再试', 'home', 3, 'error');
                        } else {
                            if ($row_state['code'] == 0) {
                                $showmessage = $commonclass->showMessage('评价成功', 'home', 3, 'right');
                            } else {
                                $showmessage = $commonclass->showMessage($row_state['ExceptionRsp']['msg'], 'home', 3, 'error');
                            }
                        }
                    } else {
                        $showmessage = $commonclass->showMessage($formrow['msg'], null, 3, 'error');
                    }
                    $this->render('//showmessage/showmessage', array('row' => $showmessage, 'model' => $model));
                }
            } else {
                $auth = urldecode(base64_decode($_GET['auth']));
                $autharr = explode('|', $auth);
                $uid = $autharr['0'];
                $orderId = $autharr['1'];

                if ($uid == Yii::app()->user->id) {

                    $apiurl = "/LdAccountServer/order/getOrderItem";  //查询订单详情
                    $params = array(
                        'GetOrderItemReq' => array(
                            'orderId' => $orderId
                        )
                    );
                    $row = $api->apiclient($apiurl, $params);
                    if ($row['GetOrderItemRsp']['orderState'] == 3) {
                        $this->render('receipt', array('row' => $row['GetOrderItemRsp'], 'model' => $model, 'orderId' => $orderId));
                    } else {
                        $showmessage = $commonclass->showMessage('此订单的状态不能确认收货并评价', 'home', 3, 'error');
                        $this->render('//showmessage/showmessage', array('row' => $showmessage, 'model' => $model));
                    }
                } else {
                    $this->redirect(Yii::app()->baseUrl);
                }
            }
        } else {
            $this->redirect(Yii::app()->baseUrl);
        }
    }

}
